package com.kaibes.module.email.sender;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/emails")
public class MailApi {
    
    @Autowired
    private MailService mailService;

    @PostMapping("/send")
    @ApiLink("发送一封邮件")
    public ResponseEntity<Object> sendEmail(@RequestBody @Validated MailContext mailContext) {
        MailTemplate template = new MailTemplate();
        template.setTitle(mailContext.getTitle());
        template.setHtml(mailContext.getEmailContent());
        
        Map<String, Object> dataModel = new HashMap<>();
        if (mailService.sendTemplateMessage(mailContext.getEmail(), template, dataModel)) {
            return ResponseFactory.ok("已发送一封邮件到地址："+mailContext.getEmail());
        } else {
            return ResponseFactory.postFailure("操作失败，可能是网站未正确设置邮件模块，请联系网站管理员");
        }
        
    }
    
}
